package com.hmall.service;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.*;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.hdmall.business.common.common.Const;
import com.hdmall.business.common.util.RabbitUtil;
import com.hmall.config.JPushConst;
import com.hdmall.business.common.common.ServerResponse;
import com.hmall.config.SpringContextUtil;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hdmall.business.common.util.NumberUtil;
import com.hmall.vo.MobileHomeMsgVo;
import com.hmall.vo.PageVo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.catalina.servlet4preview.http.PushBuilder;
import org.omg.CORBA.Any;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.*;

import static com.hdmall.business.common.util.PushTransMsg.httpPost;

/**
 * @Author zhoutao
 */
@Slf4j
@Service
public class JpushService {

    private  JPushConst jPushConst;

    private  MallDealerMapper mallDealerMapper;

    private  SysCustomerMapper customerMapper;

    private  SysUserRoleMapper sysUserRoleMapper;

    private  SysUserDealerMapper sysUserDealerMapper;

    private  MsgService msgService;

    /**
     * 下发通知消息的认证Token
     */
    private static String accessToken;

    /**
     * accessToken的过期时间
     */
    private static long tokenExpiredTime;

    private final MallPushMessageMapper mallPushMessageMapper;

    private final SysUserExtraService userExtraService;

    private final SysUserExtraMapper userExtraMapper;

    private final SysUserMapper userMapper;

    @Autowired
    public JpushService(MallDealerMapper mallDealerMapper, JPushConst jPushConst, SysUserMapper userMapper, SysCustomerMapper customerMapper, SysUserRoleMapper sysUserRoleMapper, SysUserDealerMapper sysUserDealerMapper, MsgService msgService, MallPushMessageMapper mallPushMessageMapper, SysUserExtraService userExtraService, SysUserExtraMapper userExtraMapper) {
        this.mallDealerMapper = mallDealerMapper;
        this.jPushConst = jPushConst;
        this.userMapper = userMapper;
        this.customerMapper = customerMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.sysUserDealerMapper = sysUserDealerMapper;
        this.msgService = msgService;
        this.mallPushMessageMapper = mallPushMessageMapper;
        this.userExtraService = userExtraService;
        this.userExtraMapper = userExtraMapper;
    }

    private Integer countNoReadMessage(Integer userId){

        return mallPushMessageMapper.countNoReadMessage(userMapper.selectByPrimaryKey(userId).getUsername().split("-")[0]);
    }

    private Integer countNoReadMessage(String userName) {

        return mallPushMessageMapper.countNoReadMessage(userName);
    }

    public ServerResponse<PageVo<MallPushMessage>> mobileUserMessage(String username, String type, Integer pageNum, Integer pageSize) {

        List<String> typeList;
        typeList = getTypeList(type);
        if (typeList.size() == 0) {
            typeList = null;
        }
        List<MallPushMessage> mallPushMessageList = mallPushMessageMapper.mobileUserMessage(username, typeList);
        int total = mallPushMessageList.size();

        int pageStart = (pageNum - 1) * pageSize;
        int end = Math.min(pageStart + pageSize, total);
        List<MallPushMessage> subMallPushMessageList = mallPushMessageList.subList(pageStart, end);
        PageVo<MallPushMessage> pageVo = new PageVo<>(pageNum, pageSize, total, subMallPushMessageList);
        return ServerResponse.createBySuccess(pageVo);
    }


    public void mobileSetIsRead(Integer messageId) {

        mallPushMessageMapper.mobileSetIsRead(messageId);
    }

    public ServerResponse<Integer> mobileUserMessageCount(String username) {

        int noReadCount = mallPushMessageMapper.countNoReadMessage(username);
        return ServerResponse.createBySuccess(noReadCount);
    }

    public ServerResponse mobileSetAllRead(String userName, String type) {

        List<String> typeList;
        typeList = getTypeList(type);
        if (typeList.size() == 0) {
            typeList = null;
        }
        mallPushMessageMapper.mobileSetAllRead(userName, typeList);
        return ServerResponse.createBySuccess();
    }
//    纤天下极光推送所有用户
    public void xtxJPushAll(String title, String body, String value, String masterSecret, String appKey) throws IOException {
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());

        PushPayload payloadIOS, payloadAndroid;
        payloadIOS = buildPushAllIOSObject(title, body, null, value);

        payloadAndroid = buildPushAllAndroidObject(title, body, null, value);
        // For push, all you need do is to build PushPayload object.

        try {
            PushResult resultIOS = jpushClient.sendPush(payloadIOS);
            PushResult resultAndroid = jpushClient.sendPush(payloadAndroid);
            log.info(String.valueOf(resultIOS));
            log.info(String.valueOf(resultAndroid));
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            System.out.println("Connection error, should retry later!");

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
        }

    }

    public void jPushAll(String title, String body, String type, String value, String masterSecret, String appKey, String appSecret, String appId) throws IOException {

        String sound = getSound(type);
        List<SysUser> userList = userMapper.selectAll();
        //华为全推送
        for (SysUser user : userList) {
            //先判断是否是在华为设备上登录过
            SysUserExtra userExtra = userExtraMapper.selectExtraByUserId(user.getUserId());
            if (userExtra == null || userExtra.getDeviceToken() == null || user.getDeptId() != null) {
                continue;
            }

            sendPushMessage(title, body, user.getUsername(), type, value, appSecret, appId, sound);
        }

        //存储信息
        if(!"logout".equals(type)) {
            stoneAllMessage(title, body, type, value);
        }

        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());

        PushPayload payloadIOS, payloadAndroid;
        payloadIOS = buildPushAllIOSObject(title, body, type, value);

        payloadAndroid = buildPushAllAndroidObject(title, body, type, value);
        // For push, all you need do is to build PushPayload object.

        try {
            PushResult resultIOS = jpushClient.sendPush(payloadIOS);
            PushResult resultAndroid = jpushClient.sendPush(payloadAndroid);
            log.info(String.valueOf(resultIOS));
            log.info(String.valueOf(resultAndroid));
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            System.out.println("Connection error, should retry later");

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
        }

    }

    private String getSound(String type){

        //订单审核通过 order_status 给用户
        //提交订单orderNomal orderSimple 给办事处
        String frontStatus = "order_status";
        String orderNomal = "orderNomal";
        String orderSimple = "orderSimple";
        String sound = "";
        if (frontStatus.equals(type)) {
//            sound = "mall_order_voice.m4a";
            sound = "ok3.wav";
        } else if (orderNomal.equals(type) || orderSimple.equals(type)) {
//            sound = "dealer_order_voice.m4a";
            sound = "ok.wav";
        }
        return sound;
    }
    public ServerResponse<Long> xtxJPushMethod(String title, String body, String userName, String value, String type, String masterSecret, String appKey, String appSecret, String appId) throws IOException {

//        华为推送
        SysUserExtra userExtra = userExtraMapper.selectExtraByUserName(userName.split("-")[0]);
//        if (userExtra != null && userExtra.getDeviceToken() != null) {
//            sendPushMessage(title, body, userName, type, value, appSecret, appId, null);
//        }

        //存储信息
        Long messageNo = 0L;
        //登录给前一个用户提出发送推送
        Integer messageId = -1;
        //极光推送
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());

        PushPayload payload;


        SysUserExtra extra = userExtraService.findByUserName(userName.split("-")[0]);
        String alias;
        if (extra != null) {
            alias = extra.getAlias();
        } else {
            //手机推送失败导致无法返回消息no，后期作data优化
            return ServerResponse.createBySuccess(messageNo);
        }

        if(alias.contains("WECHAT")) {
            return ServerResponse.createBySuccess();
        }

        if(!"".equals(alias)) {
            assert userExtra != null;
            payload = buildPushObject(title, userExtra.getUserId(), body, userName, type, value, alias, null, messageId);

            try {

                PushResult result = jpushClient.sendPush(payload);
                System.out.println("Got result - " + result);
            } catch (APIConnectionException e) {
                System.out.println("Connection error, should retry later-");

            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                System.out.println("HTTP Status: " + e.getStatus());
                System.out.println("Error Code: " + e.getErrorCode());
                System.out.println("Error Message: " + e.getErrorMessage());
            }
        }

        return ServerResponse.createBySuccess(messageNo);
    }

    public ServerResponse<Long> jPushMethod(String title, String body, String userName, String type, String value, String masterSecret, String appKey, String appSecret, String appId) throws IOException {

        String sound = getSound(type);
//        华为推送
        SysUserExtra userExtra = userExtraMapper.selectExtraByUserName(userName.split("-")[0]);
        if (userExtra != null && userExtra.getDeviceToken() != null) {
            sendPushMessage(title, body, userName, type, value, appSecret, appId, sound);
        }

        //存储信息
        Long messageNo = 0L;
        //登录给前一个用户提出发送推送
        String logout = "logout";
        Integer messageId = -1;
        if (!logout.equals(type)) {

            messageNo = stoneMessage(title, body, userName, type, value);
            messageId = mallPushMessageMapper.selectIdByNo(messageNo);
        }

        //极光推送
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());

        PushPayload payload;


        SysUserExtra extra = userExtraService.findByUserName(userName.split("-")[0]);
        String alias;
        if (extra != null) {
            alias = extra.getAlias();
        } else {
            //手机推送失败导致无法返回消息no，后期作data优化
            return ServerResponse.createBySuccess(messageNo);
        }

        if(alias.contains("WECHAT")) {
            return ServerResponse.createBySuccess();
        }

        if(!"".equals(alias)) {
            assert userExtra != null;
            payload = buildPushObject(title, userExtra.getUserId(), body, userName, type, value, alias, sound, messageId);


            // For push, all you need do is to build PushPayload object.
            //如果上一个用户就是这个手机，不进行推送
            //&& alias.contains(userName)
//        if (logout.equals(type)) {
//            return ServerResponse.createBySuccess(messageNo);
//        }

            try {
                PushResult result = jpushClient.sendPush(payload);
                System.out.println("Got result - " + result);

            } catch (APIConnectionException e) {
                // Connection error, should retry later
                System.out.println("Connection error, should retry later");

            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                System.out.println("Should review the error, and fix the request");
                System.out.println("HTTP Status: " + e.getStatus());
                System.out.println("Error Code: " + e.getErrorCode());
                System.out.println("Error Message: " + e.getErrorMessage());
            }
        }

        return ServerResponse.createBySuccess(messageNo);
    }

    /**
     * @Date 2018/11/9 13:00
     * @Param [title, body, type, value]
     * @return cn.jpush.api.push.model.PushPayload
     * @Description // IOS广播
     */
    private PushPayload buildPushAllIOSObject(String title, String body, String type, String value) {

        String sound = getSound(type);
        //推送前查询该用户的未读消息
        PushPayload.Builder builder = new PushPayload.Builder();
        builder.setPlatform(Platform.ios());
        builder.setAudience(Audience.all());
        IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody(title, null, body).build();

        builder.setPlatform(Platform.ios());
        IosNotification.Builder iosNotification = IosNotification.newBuilder();
        iosNotification.setAlert(iosAlert);
        iosNotification.setBadge(+1);
        if (null == sound || "".equals(sound)) {
            iosNotification.setSound("default");
        } else {
            iosNotification.setSound(sound);
        }
        iosNotification.addExtra("type", type);
        iosNotification.addExtra("value", value);
        if ("dev".equals(SpringContextUtil.getActiveProfile())) {

            builder.setNotification(Notification.newBuilder()
                    .addPlatformNotification(iosNotification.build()).build());
        } else {
            builder.setNotification(Notification.newBuilder()
                    .addPlatformNotification(iosNotification.build()).build())
                    .setOptions(Options.newBuilder().
                            setApnsProduction(true).build());
        }

        return builder.build();
    }

    /**
     * @Date 2018/11/9 13:01
     * @Param [title, body, type, value]
     * @return cn.jpush.api.push.model.PushPayload
     * @Description // 安卓广播
     *
     *
     */


    private PushPayload buildPushAllAndroidObject(String title, String body, String type, String value) {


        String sound = getSound(type);
        //推送前查询该用户的未读消息
        PushPayload.Builder builder = new PushPayload.Builder();

        builder.setPlatform(Platform.android());
        builder.setAudience(Audience.all());


        builder.setPlatform(Platform.android());
        builder.setMessage(Message.newBuilder().setMsgContent(body).addExtra("type", type).addExtra("value", value)
                .addExtra("sound", sound).setTitle(title)
                .build());

        return builder.build();
    }

    private PushPayload buildPushObject(String title, Integer userId, String body, String userName, String type, String value, String alias, String sound){
        return buildPushObject(title, userId, body, userName, type, value, alias, sound, -1);
    }

    /**
     *
     * @param title
     * @param userId
     * @param body
     * @param userName
     * @param type
     * @param value
     * @param alias
     * @param sound
     * @param messageId
     * @return
     */
    private PushPayload buildPushObject(String title, Integer userId, String body, String userName, String type, String value, String alias, String sound, Integer messageId) {

        //推送前查询该用户的未读消息
        Integer noReadMessage ;
        //即时通讯消息类型
        String messageType = "message_type";
        if (!messageType.equals(type)) {
            noReadMessage = countNoReadMessage(userId);
        } else {
            noReadMessage = 1;
        }


        //查询出上次登录在设备设备进行推送
//        alias = "IOS_hyh";
        PushPayload.Builder builder = new PushPayload.Builder();
//        builder.setAudience(Audience.alias(alias));

        IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody(title, null, body).build();
        if (alias.contains("IOS")) {
            builder.setPlatform(Platform.ios());
//            builder.setAudience(Audience.alias(alias));

            IosNotification.Builder iosNotification = IosNotification.newBuilder();
            iosNotification.setAlert(iosAlert);
            iosNotification.setBadge(noReadMessage);
            if (null == sound || "".equals(sound)) {
                iosNotification.setSound("default");
            } else {
                iosNotification.setSound(sound);
            }
            iosNotification.addExtra("type", type);
            iosNotification.addExtra("value", value);
            iosNotification.addExtra("userId", userId);
            iosNotification.addExtra("messageId", messageId);
            if ("dev".equals(SpringContextUtil.getActiveProfile())) {

                builder.setNotification(Notification.newBuilder()
                        .addPlatformNotification(iosNotification.build()).build());
            } else {
                builder.setNotification(Notification.newBuilder()
                        .addPlatformNotification(iosNotification.build()).build())
                        .setOptions(Options.newBuilder().
                                setApnsProduction(true).build());
            }
        }
        //全部默认透传消息
        else if (alias.contains("ANDROID")) {


            builder.setPlatform(Platform.android());
//            builder.setAudience(Audience.alias(alias));
            builder.setMessage(Message.newBuilder()
                    .setMsgContent(body)
                    .addExtra("type", type)
                    .addExtra("value", value)
                    .addExtra("sound", getSound(type)).addExtra("noRead", noReadMessage).addExtra("userId", userId)
                    .addExtra("messageId", messageId).setTitle(title)
                    .build());
//            }else {
//                builder.setNotification(Notification.newBuilder()
//                        .addPlatformNotification(AndroidNotification.newBuilder()
//                                .setTitle(title)
//                                .setAlert(body)
//                                .addExtra("type", type)
//                                .addExtra("value", value)
//                                .build())
//                        .build());
//            }
        }

        builder.setAudience(Audience.newBuilder().addAudienceTarget(AudienceTarget.alias(alias)).build());

        return builder.build();
    }

    /**
     * @Date 2018/11/9 13:01
     * @Param [title, body, userName, type, value, appSecret, appId, sound]
     * @return void
     * @Description // 华为消息推送方法
     */
    public void sendPushMessage(String title, String body, String userName, String type, String value, String appSecret, String appId, String sound) throws IOException {

        if (tokenExpiredTime <= System.currentTimeMillis()) {
            refreshToken(appSecret);
        }

        /*PushManager.requestToken为客户端申请token的方法，可以调用多次以防止申请token失败*/

        /*PushToken不支持手动编写，需使用客户端的onToken方法获取*/

        //目标设备Token
        JSONArray deviceTokens = new JSONArray();

        Integer userId = userMapper.selectIdByUsername(userName.split("-")[0]);

        String deviceToken = userExtraMapper.findDeviceToken(userId);

        deviceTokens.add(deviceToken);

        //仅通知栏消息需要设置标题和内容，透传消息key和value为用户自定义
        JSONObject bodyMsg = new JSONObject();

        //消息标题
        bodyMsg.put("title", title);
        //消息内容体
        bodyMsg.put("content", body);

        JSONObject param = new JSONObject();
        //定义需要打开的appPkgName
        param.put("appPkgName", "com.huawei.hms.hmsdemo");

        JSONObject action = new JSONObject();
        //类型3为打开APP，其他行为请参考接口文档设置
        action.put("type", 3);
        //消息点击动作参数
        action.put("param", param);

        JSONObject msg = new JSONObject();
        //msg.put("type", 3);//3: 通知栏消息，异步透传消息请根据接口文档设置
        msg.put("type", 1);
        //消息点击动作
        msg.put("action", action);
        //通知栏消息body内容
        msg.put("body", bodyMsg);

        //扩展信息，含BI消息统计，特定展示风格，消息折叠。
        JSONObject ext = new JSONObject();
        //设置消息标签，如果带了这个标签，会在回执中推送给CP用于检测某种类型消息的到达率和状态
        ext.put("biTag", "Trump");
        //自定义推送消息在通知栏的图标,value为一个公网可以访问的URL
        ext.put("icon", "http://pic.qiantucdn.com/58pic/12/38/18/13758PIC4GV.jpg");

        JSONObject extra = new JSONObject();
        extra.put("type", type);
        extra.put("value", value);
        extra.put("sound", sound);
        Integer realUserId = userMapper.selectByUserName1(userName).getUserId();
        extra.put("userId", realUserId);

        //华为PUSH消息总结构体
        JSONObject hps = new JSONObject();
        hps.put("msg", msg);
        hps.put("ext", ext);
        hps.put("customize", extra);

        JSONObject payload = new JSONObject();
        payload.put("hps", hps);
        String postBody = MessageFormat.format(
            "access_token={0}&nsp_svc={1}&nsp_ts={2}&device_token_list={3}&payload={4}",
            URLEncoder.encode(accessToken, "UTF-8"),
            URLEncoder.encode("openpush.message.api.send", "UTF-8"),
            URLEncoder.encode(String.valueOf(System.currentTimeMillis() / 1000), "UTF-8"),
            URLEncoder.encode(deviceTokens.toString(), "UTF-8"),
            URLEncoder.encode(payload.toString(), "UTF-8"));

        //应用级消息下发API
          String apiUrl = "https://api.push.hicloud.com/pushsend.do";
        String postUrl = apiUrl + "?nsp_ctx=" + URLEncoder.encode("{\"ver\":\"1\", \"appId\":\"" + appId + "\"}", "UTF-8");

        httpPost(postUrl, postBody, 5000, 5000);
        ServerResponse.createBySuccess();
    }

    /**
     * @Date 2018/11/9 13:07
     * @Param [appSecret]
     * @return void
     * @Description // 获得token
     */
    private void refreshToken(String appSecret) throws IOException {
        String msgBody = MessageFormat.format(
                "grant_type=client_credentials&client_secret={0}&client_id={1}",
                URLEncoder.encode(appSecret, "UTF-8"), jPushConst.HUAWEI_MALL_APPID);
      //获取认证Token的URL
        String tokenUrl = "https://login.cloud.huawei.com/oauth2/v2/token";
        String response = httpPost(tokenUrl, msgBody, 5000, 5000);
        JSONObject obj = JSONObject.fromObject(response);
        accessToken = obj.getString("access_token");
        tokenExpiredTime = System.currentTimeMillis() + obj.getLong("expires_in") * 1000;
    }


    /**
     * @Date 2018/11/7 17:34
     * @Param [title, body, userName, type, value]
     * @return java.lang.Long
     * @Description // 消息存储
     */
    public Long stoneMessage(String title, String body, String userName, String type, String value) {

        //2018/12/7
        Integer userId = userMapper.selectByUserName1(userName).getUserId();
        //如果是业务员就没有dealerId
        int dealerId = 0;


        Long messageNo = NumberUtil.createOrderNo(dealerId);


        MallPushMessage pushMessage = new MallPushMessage();
        pushMessage.setIsRead(0);
        //1是手机
        pushMessage.setMessageNo(messageNo);
        pushMessage.setDeviceType(1);
        pushMessage.setTitle(title);
        pushMessage.setType(type);
        pushMessage.setParams(value);
        pushMessage.setBody(body);
        pushMessage.setUsername(userName.split("-")[0]);
        pushMessage.setCreateTime(new Date());
        pushMessage.setUserId(userId);
        System.out.print(pushMessage.toString());
        mallPushMessageMapper.insert(pushMessage);

        return messageNo;
    }

    /**
     * @Date 2018/11/9 13:16
     * @Param [title, body, type, value]
     * @return void
     * @Description //
     *    消息所有用户存储
     *    有dept的为商铺
     */
    public void stoneAllMessage(String title, String body, String type, String value) {

        List<SysUser> userList = userMapper.selectAll();
        for (SysUser user : userList) {
            if (user.getDeptId() == null) {
                stoneMessage(title, body, user.getUsername(), type, value);
            }
        }

    }

    /**
     * @Date 2019/05/28 13:16
     * @Param [customerUserId, date, status, value]
     * @return com.hmall.common.ServerResponse<java.lang.String>
     * @Description //
     * 后台消息推送
     *
     *     0: 评论
     *     1: 文章/动态
     *     2：转发
     *     3: 关注
     *     4: 系统通知
     *     title = getTitle(username, "拿样申请");
     *                 body = "客户" + username + "于" + dateStr + "提出了拿样订单申请，订单号是" + value + "，请您密切关注相关信息";
     *                 type = "orderSimple";
     *                 break;
     *
     */
    public ServerResponse<String> feedbackPushMessage(String userName, Integer status, String value) throws IOException, ParseException {

        //系统通知
        if (status == 0) {
            /*"sopMessageId" : 18,
                    "isRead" : 0,
                    "content" : "【APP名称】您好，销售1(销售)于2019-06-18-10-44-40-638提交订单编号为1233的订单问题反馈，请您尽快处理相关问题反馈！",
                    "title" : "问题受理通知 ",
                    "sopOrderId" : 11,
                    "userId" : 383,
                    "createTime"*/
            try {
                Gson gson = new Gson();
                HashMap<String, Object> hashMap = gson.fromJson(value, HashMap.class);
                String body = (String)hashMap.get("content");
                String title = (String)hashMap.get("title");
                Double id = (Double) hashMap.get("sopOrderId");
                Integer intId = id.intValue();
                String sopId = intId.toString();
                System.out.print(hashMap);
                xtxJPushMethod(title, body, userName, sopId, "sop_order","40bf58b358efe4c555690250", "71942b086fac751114938c15", jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID);
                return ServerResponse.createBySuccess("发送成功");
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByError();
            }
        }
        return ServerResponse.createBySuccess("发送成功");
    }

    /**
     * @Date 2019/05/28 13:16
     * @Param [customerUserId, date, status, value]
     * @return com.hmall.common.ServerResponse<java.lang.String>
     * @Description //
     * 后台消息推送
     *
     *     0: 评论
     *     1: 文章/动态
     *     2：转发
     *     3: 关注
     *     4: 系统通知
     *
     */
    public ServerResponse<String> xtxPushMessage(String userName, Date date, Integer status, String value) throws IOException, ParseException {

        
        //系统通知
        String title = "";
        if (status == 4) {
            try {
                Gson gson = new Gson();
                HashMap<String, Object> hashMap = gson.fromJson(value, HashMap.class);
                String body = (String)hashMap.get("message");
                RabbitUtil.rabbitPushForDirect("xtx_direct", "XTXPC-" + userName, "XTXPC-" + userName, value);
                xtxJPushMethod(title, body, userName, value, null,jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID);
                return ServerResponse.createBySuccess("发送成功");
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByError();
            }
        }
        RabbitUtil.rabbitPushForDirect("xtx_direct", userName, userName, value);
        RabbitUtil.rabbitPushForDirect("xtx_direct", userName, userName, value);
        RabbitUtil.rabbitPushForDirect("xtx_direct", userName, userName, value);
        return ServerResponse.createBySuccess("发送成功");
    }
       /* String body = "";
        String title = "";
        String type = "";
        //日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String dateStr = calendar.getTime().toLocaleString();
        SysUser user;
        Integer deptId = 0;
        String username = "";
        /*
        switch (status) {
            case 0: {
                title = getTitle(username, "订单审核通知");
                String dealerName = mallDealerMapper.selectAllByDeptId(deptId).getDealerName();
                body = "您好，" + dealerName + username + "业务员于" + date.toLocaleString() + "已提交订单编号为" + value + "的订单，请您尽快核实该订单相关信息！";
                type = "orderExam";
                break;
            }
            case 1: {
                title = getTitle(username, "订单催审");
                body = "您好," + username + "跟单员正在等待审核订单编号为" + value + "的订单，请您尽快审核该条订单！";
                type = "financeExam";
                break;
            }
            //计划提交申请
            case 2: {
                title = getTitle(username, "生产计划提交申请");
                body = "客户" + username + "已对其" + calendar.getTime().getYear() + "年" + calendar.getTime().getMonth() + "月" + "生产计划提交，请您密切关注相关信息";
                type = "waitForAudit";
                break;
            }
            //拿样
            case 3: {
                title = getTitle(username, "拿样申请");
                body = "客户" + username + "于" + dateStr + "提出了拿样订单申请，订单号是" + value + "，请您密切关注相关信息";
                type = "orderSimple";
                break;
            }
            //普通订单申请
            case 4: {
                title = getTitle(username, "订单审核申请");
                body = "客户" + username + "于" + dateStr + "提出了订单审核申请，订单号是" + value + "，请您密切关注相关信息";
                type = "orderNomal";
                break;
            }
            default: {
                break;
            }
        }*/
//        //如果是nc推送，只是针对这个后台用户推送
//        if(status == 4){
//            String []sValue = value.split("-");
//            Long messageNo = jPushMethod(title, body, username,type, sValue[0], jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();
//            Integer messageId = mallPushMessageMapper.selectIdByNo(messageNo);
////            msgService.backDirectPush(messageId, username, type, body, title, value);
//            return ServerResponse.createBySuccess("发送成功");
//        }else {
//            try {
//                Gson gson = new Gson();
//                HashMap<String, Object> hashMap = gson.fromJson(value, HashMap.class);
//                Integer messageId = (Integer)hashMap.get("messageId");
//                RabbitUtil.rabbitPushForDirect("xtx_direct", "XTXIOS-15669055861", "IOS-15669055861", value);
//
//            } catch (Exception e) {
//                e.printStackTrace();
//                return ServerResponse.createByError();
//            }
//            return ServerResponse.createBySuccess("发送成功");
//        }
//    }


    /**
     * @Date 2018/11/9 13:16
     * @Param [customerUserId, date, status, value]
     * @return com.hmall.common.ServerResponse<java.lang.String>
     * @Description //
     * 后台消息推送
     *
     *     1.用户拿样申请
     *     2.普通订单申请
     *     3.付款超时提醒 12h
     *     4.付款消息提醒
     *     5.收货确认
     *     6.差评提示
     *     7.生产计划提交申请
     *
     *     8 订单催审
     *     9.业务员提交订单
     */
    public ServerResponse<String> backPushMessage(Integer customerUserId, Date date, Integer status, String value) throws IOException, ParseException {

        String body = "";
        String title = "";
        String type = "";
        //日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String dateStr = calendar.getTime().toLocaleString();
        SysUser user;
        Integer deptId = 0;
        String username = "";
        if (status != 13) {
            user = userMapper.selectByPrimaryKey(customerUserId);
            deptId = user.getDeptId();
            username = user.getUsername();
        }

        switch (status) {
            case 9: {
                title = getTitle(username, "订单审核通知");
                String dealerName = mallDealerMapper.selectAllByDeptId(deptId).getDealerName();
                body = "您好，" + dealerName + username + "业务员于" + date.toLocaleString() + "已提交订单编号为" + value + "的订单，请您尽快核实该订单相关信息！";
                type = "orderExam";
                break;
            }
            case 8: {
                title = getTitle(username, "订单催审");
                body = "您好," + username + "跟单员正在等待审核订单编号为" + value + "的订单，请您尽快审核该条订单！";
                type = "financeExam";
                break;
            }
            //计划提交申请
            case 7: {
                title = getTitle(username, "生产计划提交申请");
                body = "客户" + username + "已对其" + calendar.getTime().getYear() + "年" + calendar.getTime().getMonth() + "月" + "生产计划提交，请您密切关注相关信息";
                type = "waitForAudit";
                break;
            }
            //拿样
            case 1: {
                title = getTitle(username, "拿样申请");
                body = "客户" + username + "于" + dateStr + "提出了拿样订单申请，订单号是" + value + "，请您密切关注相关信息";
                type = "orderSimple";
                break;
            }
            //普通订单申请
            case 2: {
                title = getTitle(username, "订单审核申请");
                body = "客户" + username + "于" + dateStr + "提出了订单审核申请，订单号是" + value + "，请您密切关注相关信息";
                type = "orderNomal";
                break;
            }
            //付款超时提醒
            case 3: {
                title = getTitle(username, "付款超时提醒");
                body = "订单" + value + "的付款时间12小时后即将到期，请您密切关注信息";
                type = "orderTimeOut";
                break;
            }
            //付款消息提醒
            case 4: {
                title = getTitle(username, "付款消息");
                body = "客户" + username + "于" + dateStr + "上传了订单" + value + "的定金付款凭条，请您密切关注相关信息";
                type = "orderPayed";
                break;
            }
            //收货确认
            case 5: {
                title = getTitle(username, "收货确认");
                body = "客户" + username + "于" + dateStr + "对订单" + value + "进行了第一次收货确认，请您密切关注相关信息";
                type = "orderReceive";
                break;
            }
            //订单差评提示
            case 6: {
                title = getTitle(username, "订单差评");
                body = "客户" + username + "于" + dateStr + "对订单" + value + "提交了差评，请您密切关注相关信息";
                type = "orderBadCommit";
                break;
            }
            //nc系统结束给业务员作极光推送
            case 10:{
                title = "NC系统插入完成";
                String []sValue = value.split("-");
                body = "您好，您审核通过的" + sValue[0] + "，子订单号为" + sValue[1] + "的订单已于" + calendar.getTime().toLocaleString() + "提交至nc系统跟单员处，请您密切关注后续动向";
                type = "orderNcFinish";
                break;
            }
            //资质审核给后台发送推送
            case 12:{
                title = "资质认证申请";
                body = "您好，用户" + username + "已于"+ dateStr + "提交公司资质认证申请，请您尽快审核相关认证资质信息。";
                type = "examApply";
                break;
            }
            //竞拍申请推送
            case 11:{
                title = "竞拍申请";
                body = "您好，用户" + username + "已于" + dateStr + "申请第" + value + "期商品竞拍资格，请您尽快审核竞拍申请信息";
                type = "auctionApply";
                break;
            }
            //资质审核给后台发送推送您好，产品xxxx（物料编码A）、xxxx（物料编码B）
            // 已于xx年xx月xx日xx时分别减少xx吨、xx吨，
            // 现在剩余库存量分别为xx吨、xx吨，望请悉知！
            case 13:{
                title = "库存变更";
                String []sValue = value.split("-");
                body = "您好，" + sValue[0] + "已于"+ dateStr + "分别减少" + sValue[1] + "，现在剩余库存量分别为" + sValue[2] + "，望请悉知！";
                type = "stockChange";
                break;
            }
            default: {
                break;
            }
        }

        //如果是nc推送，只是针对这个后台用户推送
        if(status == 10){
            String []sValue = value.split("-");
            Long messageNo = jPushMethod(title, body, username,type, sValue[0], jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();
            Integer messageId = mallPushMessageMapper.selectIdByNo(messageNo);
//            msgService.backDirectPush(messageId, username, type, body, title, value);
            return ServerResponse.createBySuccess("发送成功");
        }


        //2019/1/21
        //用户资质申请给后台发送推送
        //menu资质审核->sys_role_menu->sys_user

        //2019/1/21
        //用户提出竞拍发出推送

        if(status == 12 || status == 11) {
            String menuContent;
            if(status == 12) {
                 menuContent = "资质审核";
            }else{
                menuContent = "竞拍审核";
            }
            List<String> backUsernameList = userMapper.selectUsernameByExamRule(menuContent);
            for (String backUsername : backUsernameList) {
                Long messageNo = jPushMethod(title, body, username, type, value, jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();
                Integer messageId = mallPushMessageMapper.selectIdByNo(messageNo);
                msgService.backDirectPush(messageId, backUsername, type, body, title, value);

            }
            return ServerResponse.createBySuccess("资质审核推送后台发送成功");
        }

        if (status == 13) {
            List<SysUser> userList = userMapper.selectByNewDeptId(customerUserId);
            for (SysUser myUser: userList) {
                String []sValue = value.split("-");
                Long messageNo = jPushMethod(title, body, myUser.getUsername(), type, sValue[0], jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();

                Integer messageId = mallPushMessageMapper.selectIdByNo(messageNo);
//                msgService.backDirectPush(messageId, myUser.getUsername(), type, body, title, value);
            }
            return ServerResponse.createBySuccess("库存消息！Success");

        }



        //2018/10/17
        //跟单员需要给资金消息推送
        //后台访问方式修改
        //roleId = 112时
        if (deptId != null) {
            if (deptId.equals(Const.MERCH_DEPT_ID)) {
                int roleId = 112;
                List<Integer> financeUserIdList = sysUserRoleMapper.selectUserIdByRole(roleId);
                List<SysUser> financeUserList = userMapper.selectByUserIdList(financeUserIdList);
                for (SysUser financeUser : financeUserList) {
                    Long messageNo = jPushMethod(title, body, financeUser.getUsername(), type, value, jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();
                    Integer messageId = mallPushMessageMapper.selectIdByNo(messageNo);
                    //业务员pc推送
                    msgService.backDirectPush(messageId, financeUser.getUsername(), type, body, title, value);
                }
            } else {
                //给所有跟单员和资金发送推送
                Integer dealerId = mallDealerMapper.selectAllByDeptId(deptId).getDealerId();
                //先找到所有的跟单员 sys_user_dealer 根据业务员id找到dealerId 根据dealerId找到跟单员的Id
                List<Integer> merchUserIdList = sysUserDealerMapper.selectByDealerId(dealerId);

                //找到所有的资金
                List<Integer> financeUserIdList = sysUserRoleMapper.selectUserIdByRole(112);

                List<Integer> allUserIdList = new ArrayList<>();
                allUserIdList.addAll(financeUserIdList);
                allUserIdList.addAll(merchUserIdList);
                List<SysUser> allUserList = userMapper.selectByUserIdList(allUserIdList);

                for (SysUser sysUser : allUserList) {
                    Long messageNo = jPushMethod(title, body, sysUser.getUsername(), type, value, jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();
                    Integer messageId = mallPushMessageMapper.selectIdByNo(messageNo);
                    //业务员pc推送
                    msgService.backDirectPush(messageId, sysUser.getUsername(), type, body, title, value);
                }

            }
        } else {
            //插入数据库在手机推送里面

            //是推送给业务员不是用户

            //根据用户找到他绑定的业务员

            Integer salesmanId = customerMapper.selectByUserId(customerUserId).getSalesmanId();
            username = userMapper.selectByPrimaryKey(salesmanId).getUsername();
            //业务员手机推送

            Long messageNo = jPushMethod(title, body, username, type, value, jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();
            Integer messageId = mallPushMessageMapper.selectIdByNo(messageNo);
            //业务员pc推送
            msgService.backDirectPush(messageId, username, type, body, title, value);

            Integer manageId = mallDealerMapper.selectManageIdBySalesmanId(salesmanId);
            if (null != manageId) {
                String manageUsername = userMapper.selectByPrimaryKey(manageId).getUsername();

                //办事处管理员手机推送
                Long manageMessageNo = jPushMethod(title, body, manageUsername, type, value, jPushConst.JPUSH_BACK_SECRET, jPushConst.JPUSH_BACK_APPKEY, jPushConst.HUAWEI_BACK_SECRET, jPushConst.HUAWEI_BACK_APPID).getData();
                //办事处管理员pc推送
                Integer manageMessageId = mallPushMessageMapper.selectIdByNo(manageMessageNo);
                msgService.backDirectPush(manageMessageId, manageUsername, type, body, title, value);
            }
        }
        return ServerResponse.createBySuccess("发送成功");
    }


    private String getTitle(String username, String type) {

        return "来自" + username + "的" + type;
    }

    public ServerResponse<List<MobileHomeMsgVo>> mobileHomeMessage(String username) {


        String []typeList = {"orderMsg", "systemMsg"};
        List<MobileHomeMsgVo> mobileHomeMsgVoList = new ArrayList<>();
        for (String type : typeList) {
            MobileHomeMsgVo mobileHomeMsgVo = new MobileHomeMsgVo();
            mobileHomeMsgVo.setType(type);
            List<String> tTypeList;
            tTypeList = getTypeList(type);
            int count = mallPushMessageMapper.selectCountByType(username, tTypeList);
            mobileHomeMsgVo.setNoReadMessageNum(count);
            //先是未读的最近的第一条
            MallPushMessage mallPushMessage = mallPushMessageMapper.selectOneByType(username, tTypeList, null);
            //如果没有默认最近一条
            if (mallPushMessage == null) {
                mallPushMessage = mallPushMessageMapper.selectOneByType(username, tTypeList, 0);
            }

            mobileHomeMsgVo.setFirstMallPushMessage(mallPushMessage);
            mobileHomeMsgVoList.add(mobileHomeMsgVo);
        }

        return ServerResponse.createBySuccess(mobileHomeMsgVoList);
    }

    public ServerResponse mobileDeleteMsg(String username, Integer messageId) {

        MallPushMessage mallPushMessage = mallPushMessageMapper.selectByMessageId(username, messageId);
        if (null == mallPushMessage) {
            return ServerResponse.createByErrorMessage("请勿删除其他用户的消息");
        }
        try {
            mallPushMessageMapper.deleteByPrimaryKey(messageId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess("删除成功");

    }

    private List<String> getTypeList(String type) {
        List<String> typeList = new ArrayList<>();
        if ("systemMsg".equals(type)) {
            typeList.add("cer_status");
            typeList.add("stockChange");
        } else if ("orderMsg".equals(type)) {
            typeList.add("order_status");
            typeList.add("orderNomal");
            typeList.add("orderSimple");
            typeList.add("financeExam");
            typeList.add("orderExam");
            typeList.add("orderNcFinish");
            typeList.add("auctionApply");
            typeList.add("passAuctionApply");
        }

        return typeList;
    }

    /**
     * @return void
     * @Date 2018/11/7 15:49
     * @Param [ios, username, messageJsonStr]
     * @Description // 极光推送
     */
    void remindMessage(String sendName, Integer userId, String content, String alias, String messageJsonStr, String secret, String appKey) {

        //极光推送
        JPushClient jpushClient = new JPushClient(secret, appKey, null, ClientConfig.getInstance());

        PushPayload payload;

        payload = buildPushObject(sendName, userId, content, null, "message_type", messageJsonStr, alias, "");

        try {
            PushResult result = jpushClient.sendPush(payload);
            log.info(String.valueOf(result));
        } catch (APIConnectionException | APIRequestException e) {
            log.info("推送失败");
        }
        ServerResponse.createBySuccess("推送成功");
    }
}
